package com.why.controller;

import com.why.entity.Result;
import com.why.entity.User;
import com.why.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author new wei
 * @date 2022/5/26 22:29
 */
@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    IUserService userService;

    @RequestMapping("foretPassword")
    public String foretPassword(){
        return "foretPassword";
    }

    @RequestMapping("loginOK")
    public Result loginOK(){
        // 获取到用户登陆的信息
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        // 验证是否是 UserDetails 类型
        if (principal instanceof UserDetails){
            return  new Result(200,"登陆成功",principal);
        }else {
            return  new Result(201,"登陆失败","");
        }
    }

    @RequestMapping("loginFAIL")
    public Result loginFAIL(){
        return  new Result(202,"用户名密码错误","");
    }

    @RequestMapping("noLogin")
    public ResponseEntity noLogin(){
        return new ResponseEntity(new Result(300,"尚未登陆",""),HttpStatus.FORBIDDEN);
    }
    @RequestMapping("loginoutOK")
    public Result loginoutOK(){
        return new Result(200,"登出成功","已经登出");
    }

    @RequestMapping("register")
    public Result<String> register(@RequestBody User user){
        boolean b = userService.save(user);
        if (b){
            return new Result<>(200,"","注册成功");
        }else {
            return new Result<>(400,"注册失败","注册失败");
        }
    }


}
